<template>
  <div class="profile-container">
    <!-- 顶部账号信息卡片 -->
    <div class="page-header">
      <div
        class="header-bg"
        :style="{
          backgroundImage: `url(${userInfo.coverImage || '/images/default-cover.jpg'})`,
        }"
      ></div>
      <div class="container mx-auto px-4 py-8">
        <div class="header-content">
          <div class="user-profile">
            <div class="avatar-section">
              <div
                class="avatar-wrapper cursor-pointer"
                @click="showImageEditor = true"
              >
                <el-avatar :size="120" :src="userInfo.avatar" />
                <div class="avatar-mask">
                  <icon-camera />
                  <div class="text">更换头像</div>
                </div>
              </div>
            </div>
            <div class="info-section">
              <h2 class="name">{{ userInfo.name }}</h2>
              <div class="account-type">
                <a-tag :color="userInfo.isOfficial ? 'red' : 'blue'">
                  {{ userInfo.isOfficial ? "官方账号" : "管理员账号" }}
                </a-tag>
                <a-tag color="green" v-if="userInfo.isOfficial">认证账号</a-tag>
              </div>
              <div class="brief">
                {{
                  userInfo.introduction || "这个管理员很懒，还没有填写个人简介"
                }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 个人信息概览卡片 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :span="24">
        <a-card class="overview-card" :bordered="false">
          <div class="stats-wrapper">
            <div class="stats">
              <div class="stat-item">
                <div class="value">{{ userInfo.loginCount }}</div>
                <div class="label">登录次数</div>
              </div>
              <div class="stat-item">
                <div class="value">{{ userInfo.operationCount }}</div>
                <div class="label">操作次数</div>
              </div>
              <div class="stat-item">
                <div class="value">{{ userInfo.lastLoginDays }}</div>
                <div class="label">最近登录(天)</div>
              </div>
              <div class="stat-item" v-if="userInfo.isOfficial">
                <div class="value">{{ userInfo.publishCount }}</div>
                <div class="label">发布内容</div>
              </div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 详细信息和安全信息 -->
    <a-row :gutter="[16, 16]" style="margin-top: 16px">
      <a-col :span="24" :lg="16">
        <a-card class="general-card" :bordered="false">
          <template #title>
            <div class="card-title">
              <icon-user style="margin-right: 8px" />基本信息
            </div>
          </template>
          <a-form
            :model="formData"
            @submit="handleSubmit"
            layout="vertical"
            :style="{ width: '100%' }"
          >
            <a-row :gutter="[16, 16]">
              <a-col :span="12">
                <a-form-item
                  field="accountId"
                  label="账号ID"
                  validate-trigger="blur"
                  required
                >
                  <a-input
                    v-model="formData.accountId"
                    placeholder="系统自动生成"
                    disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="name"
                  label="姓名"
                  validate-trigger="blur"
                  required
                >
                  <a-input v-model="formData.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="nickname"
                  label="昵称"
                  validate-trigger="blur"
                >
                  <a-input
                    v-model="formData.nickname"
                    placeholder="请输入昵称"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="accountType"
                  label="账号类型"
                  validate-trigger="blur"
                  required
                >
                  <a-select
                    v-model="formData.accountType"
                    placeholder="请选择账号类型"
                    disabled
                  >
                    <a-option value="official">官方账号</a-option>
                    <a-option value="admin">管理员账号</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="email"
                  label="邮箱"
                  validate-trigger="blur"
                  required
                >
                  <a-input v-model="formData.email" placeholder="请输入邮箱">
                    <template #append>
                      <a-tag color="green" v-if="formData.emailVerified"
                        >已验证</a-tag
                      >
                      <a-tag color="red" v-else>未验证</a-tag>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  field="phone"
                  label="手机号"
                  validate-trigger="blur"
                  required
                >
                  <a-input v-model="formData.phone" placeholder="请输入手机号">
                    <template #append>
                      <a-tag color="green" v-if="formData.phoneVerified"
                        >已验证</a-tag
                      >
                      <a-tag color="red" v-else>未验证</a-tag>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item field="introduction" label="个人简介">
                  <a-textarea
                    v-model="formData.introduction"
                    placeholder="请输入个人简介"
                    :auto-size="{ minRows: 3, maxRows: 5 }"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <div class="form-actions">
              <a-space>
                <a-button
                  type="primary"
                  html-type="submit"
                  :loading="submitting"
                >
                  保存修改
                </a-button>
                <a-button @click="resetForm"> 重置 </a-button>
                <a-button type="outline" status="success" @click="exportProfile">
                  导出资料
                </a-button>
              </a-space>
            </div>
          </a-form>
        </a-card>
      </a-col>

      <a-col :span="24" :lg="8">
        <a-card class="general-card" :bordered="false">
          <template #title>
            <div class="card-title">
              <icon-calendar style="margin-right: 8px" />最近登录
            </div>
          </template>
          <a-timeline>
            <a-timeline-item
              v-for="record in paginatedLoginRecords"
              :key="record.loginTime"
              :dot-color="record.status === 'success' ? 'green' : 'red'"
            >
              <div class="login-record">
                <div class="time">{{ record.loginTime }}</div>
                <div class="info">
                  <div>IP：{{ record.ip }}</div>
                  <div>地点：{{ record.location }}</div>
                  <div>设备：{{ record.device }}</div>
                </div>
                <a-tag :color="record.status === 'success' ? 'green' : 'red'">
                  {{ record.status === "success" ? "登录成功" : "登录失败" }}
                </a-tag>
              </div>
            </a-timeline-item>
          </a-timeline>
          
          <!-- 分页控制 -->
          <div class="pagination-wrapper" v-if="totalLoginPages > 1">
            <a-pagination
              v-model:current="currentLoginPage"
              :total="limitedLoginRecords.length"
              :page-size="loginPageSize"
              simple
              size="small"
              :hide-on-single-page="true"
            />
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 头像编辑器组件 -->
    <ImageEditor
      v-model="showImageEditor"
      upload-action="/api/admin/upload-avatar"
      title="更换头像"
      :aspect-ratio="1"
      :history-images="avatarHistory"
      @success="handleAvatarSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconCamera,
  IconUser,
  IconCalendar,
} from "@arco-design/web-vue/es/icon";
import { useUserStore } from "@/stores/user";
import ImageEditor from "@/components/common/ImageEditor.vue";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

const userStore = useUserStore();
const submitting = ref(false);
const showImageEditor = ref(false);

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function(...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 用户基本信息（默认测试数据）
const userInfo = ref({
  name: "张三",
  role: "admin",
  avatar: "/images/avatar.jpg",
  coverImage: "/images/default-cover.jpg",
  email: "zhangsan@example.com",
  phone: "13800138000",
  introduction: "资深系统管理员，负责系统的日常运维和管理工作。",
  loginCount: 128,
  operationCount: 1024,
  lastLoginDays: 1,
  isOfficial: false,
  publishCount: 0,
});

// 头像历史记录（默认测试数据）
const avatarHistory = ref([
  {
    url: "/images/avatar-history-1.jpg",
    createTime: "2024-03-01 10:00:00",
  },
  {
    url: "/images/avatar-history-2.jpg",
    createTime: "2024-02-28 15:30:00",
  },
]);

// 登录记录（默认测试数据）
const loginRecords = ref([
  {
    loginTime: "2024-03-02 14:30:00",
    ip: "192.168.1.1",
    location: "广西贵港",
    device: "Chrome / Windows 10",
    status: "success",
  },
  {
    loginTime: "2024-03-01 09:15:00",
    ip: "192.168.1.2",
    location: "广西贵港",
    device: "Firefox / Windows 10",
    status: "success",
  },
  {
    loginTime: "2024-02-28 18:20:00",
    ip: "192.168.1.3",
    location: "广西南宁",
    device: "Safari / macOS",
    status: "failed",
  },
]);

// 表单数据
const formData = reactive({
  accountId: "GG2024001",
  name: "",
  nickname: "",
  accountType: "admin",
  email: "",
  emailVerified: true,
  phone: "",
  phoneVerified: true,
  introduction: "",
});

// 登录记录分页相关的状态
const loginPageSize = 3; // 每页显示记录数
const maxLoginRecords = 21; // 最多显示的记录数
const currentLoginPage = ref(1);

// 限制最大记录数
const limitedLoginRecords = computed(() => {
  return loginRecords.value.slice(0, maxLoginRecords);
});

// 计算总页数
const totalLoginPages = computed(() => {
  return Math.ceil(limitedLoginRecords.value.length / loginPageSize);
});

// 当前页的登录记录
const paginatedLoginRecords = computed(() => {
  const start = (currentLoginPage.value - 1) * loginPageSize;
  const end = start + loginPageSize;
  return limitedLoginRecords.value.slice(start, end);
});

// 获取管理员个人信息
const fetchProfileData = async () => {
  try {
    const response = await service.get("/admin/profile");
    console.log("获取到的个人信息数据:", response.data);
    
    // 提取数据，确保有默认值
    const data = response.data;
    
    // 计算最近登录天数
    let lastLoginDays = 0;
    if (data.last_login_time || data.lastLoginTime) {
      const lastLoginTime = new Date(data.last_login_time || data.lastLoginTime);
      const now = new Date();
      const diffTime = Math.abs(now - lastLoginTime);
      lastLoginDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    }
    
    // 更新用户信息
    userInfo.value = {
      ...userInfo.value, // 保留默认值
      ...data,
      // 用户名和昵称映射（数据库中username是用户名，real_name是真实姓名）
      name: data.real_name || data.realName || data.name || data.username || "",
      nickname: data.nickname || data.username || "",
      // 确保统计数据正确显示，优先使用后端数据，否则用0
      loginCount: data.login_count || data.loginCount || 0,
      operationCount: data.operation_count || data.operationCount || 0,
      lastLoginDays: data.lastLoginDays || lastLoginDays || 0,
      // 其他字段映射
      avatar: data.avatar || "/images/avatar.jpg",
      introduction: data.introduction || "这个管理员很懒，还没有填写个人简介",
      isOfficial: data.is_official || data.isOfficial || false
    };
    
    // 更新表单数据
    formData.accountId = data.id || data.accountId || "GG2024001";
    formData.name = data.real_name || data.realName || data.name || data.username || "";
    formData.nickname = data.nickname || data.username || "";
    formData.accountType = data.accountType || (data.is_official ? "official" : "admin");
    formData.email = data.email || "";
    formData.emailVerified = data.email_verified || data.emailVerified || !!data.email;
    formData.phone = data.phone || "";
    formData.phoneVerified = data.phone_verified || data.phoneVerified || !!data.phone;
    formData.introduction = data.introduction || "";
    
    // 将response的原始数据打印出来，帮助调试
    console.log("用户信息处理后:", userInfo.value);
    console.log("表单数据处理后:", formData);
  } catch (error) {
    console.error("获取个人信息失败:", error);
    // 使用默认测试数据
    resetForm();
  }
};

// 获取登录记录
const fetchLoginRecords = async () => {
  try {
    const response = await service.get("/admin/login-records");
    // 对返回的数据进行处理
    const records = response.data.records || response.data || loginRecords.value;
    
    // 处理数据格式
    loginRecords.value = records.map(record => {
      return {
        ...record,
        // 处理IP地址：将IPv6的本地地址转换为"内网登录"
        ip: formatIpAddress(record.ip),
        // 格式化时间
        loginTime: formatDateTime(record.loginTime),
        // 保持原始数据以备需要
        rawIp: record.ip,
        rawLoginTime: record.loginTime
      };
    });
    
    // 重置当前页为第一页
    currentLoginPage.value = 1;
  } catch (error) {
    console.error("获取登录记录失败:", error);
    // 使用默认测试数据，但也应用相同的格式化
    loginRecords.value = loginRecords.value.map(record => ({
      ...record,
      ip: formatIpAddress(record.ip),
      loginTime: formatDateTime(record.loginTime)
    }));
  }
};

// 格式化IP地址
const formatIpAddress = (ip) => {
  // 处理常见的本地IP表示
  if (ip === "0:0:0:0:0:0:0:1" || ip === "::1" || ip === "127.0.0.1") {
    return "内网登录";
  }
  // 私有IP地址范围
  if (ip.startsWith("10.") || 
      ip.startsWith("172.16.") || 
      ip.startsWith("192.168.") || 
      ip.startsWith("169.254.")) {
    return `内网IP (${ip})`;
  }
  return ip;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return "未知时间";
  
  try {
    // 解析ISO 8601格式的时间字符串
    const date = new Date(dateTimeStr);
    
    // 获取本地日期和时间部分
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    // 使用更友好的格式
    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  } catch (e) {
    console.error("日期格式化错误:", e);
    return dateTimeStr;
  }
};

// 获取头像历史
const fetchAvatarHistory = async () => {
  try {
    const response = await service.get("/admin/avatar-history");
    avatarHistory.value = response.data || avatarHistory.value;
  } catch (error) {
    console.error("获取头像历史失败:", error);
    // 使用默认测试数据
  }
};

// 处理头像上传成功
const handleAvatarSuccess = async ({ url }) => {
  try {
    userInfo.value.avatar = url;
    // 更新全局用户状态中的头像信息
    userStore.updateAvatar(url);
    // 更新头像历史
    await fetchAvatarHistory();
    Message.success("头像更新成功");
  } catch (error) {
    console.error("更新头像失败:", error);
    Message.error("头像更新失败");
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    submitting.value = true;
    
    // 提交表单数据到后端
    const response = await service.put("/admin/profile", {
      name: formData.name,
      nickname: formData.nickname,
      email: formData.email,
      phone: formData.phone,
      introduction: formData.introduction
    });
    
    Message.success("保存成功");
    
    // 更新用户信息
    await fetchProfileData();
  } catch (error) {
    console.error("保存失败:", error);
    Message.error(error.response?.data?.message || "保存失败");
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  formData.name = userInfo.value.name;
  formData.nickname = userInfo.value.nickname || "小张";
  formData.email = userInfo.value.email;
  formData.phone = userInfo.value.phone;
  formData.introduction = userInfo.value.introduction;
};

// 导出个人资料为Excel
const exportProfile = () => {
  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  
  // 个人基本信息
  const profileData = [
    ["账号信息", ""],
    ["账号ID", formData.accountId],
    ["姓名", formData.name],
    ["昵称", formData.nickname],
    ["账号类型", formData.accountType === "admin" ? "管理员账号" : "官方账号"],
    ["邮箱", formData.email],
    ["邮箱验证", formData.emailVerified ? "已验证" : "未验证"],
    ["手机号", formData.phone],
    ["手机验证", formData.phoneVerified ? "已验证" : "未验证"],
    ["个人简介", formData.introduction],
    ["登录次数", userInfo.value.loginCount],
    ["操作次数", userInfo.value.operationCount],
    ["最近登录(天)", userInfo.value.lastLoginDays],
  ];
  
  // 登录记录数据
  const loginData = [
    ["登录时间", "IP地址", "登录地点", "登录设备", "状态"],
    ...loginRecords.value.map(record => [
      record.loginTime,
      record.ip,
      record.location,
      record.device,
      record.status === "success" ? "登录成功" : "登录失败"
    ])
  ];
  
  // 创建工作表
  const profileSheet = XLSX.utils.aoa_to_sheet(profileData);
  const loginSheet = XLSX.utils.aoa_to_sheet(loginData);
  
  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(workbook, profileSheet, "个人资料");
  XLSX.utils.book_append_sheet(workbook, loginSheet, "登录记录");
  
  // 导出Excel
  XLSX.writeFile(workbook, `管理员个人资料_${formData.name}_${new Date().toISOString().split('T')[0]}.xlsx`);
};

// 页面加载时获取数据
onMounted(async () => {
  // 使用setTimeout延迟数据加载，避免一次性触发过多的DOM更新
  setTimeout(async () => {
    await fetchProfileData();
    setTimeout(async () => {
      await fetchLoginRecords();
      setTimeout(async () => {
        await fetchAvatarHistory();
      }, 100);
    }, 100);
  }, 100);

  // 添加ResizeObserver错误处理
  const originalError = console.error;
  console.error = (...args) => {
    if (args[0]?.includes?.('ResizeObserver') || 
        args[0]?.message?.includes?.('ResizeObserver') ||
        args[0]?.toString?.()?.includes?.('ResizeObserver')) {
      // 忽略ResizeObserver错误
      return;
    }
    originalError.apply(console, args);
  };
});

// 组件卸载前的清理工作
onBeforeUnmount(() => {
  // 确保重置任何可能的监听
  if (window.__resizeObserver) {
    window.__resizeObserver.disconnect();
  }
});
</script>

<style lang="less" scoped>
.profile-container {
  .page-header {
    position: relative;
    margin: -16px -16px 0;
    overflow: hidden;

    .header-bg {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 200px;
      background-size: cover;
      background-position: center;
      filter: blur(10px);
      transform: scale(1.1);

      &::after {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.4);
      }
    }

    .header-content {
      position: relative;
      z-index: 1;

      .user-profile {
        display: flex;
        align-items: flex-start;
        color: #fff;

        .avatar-section {
          margin-right: 24px;

          .avatar-wrapper {
            position: relative;
            width: 120px;
            height: 120px;
            border-radius: 50%;
            overflow: hidden;
            border: 4px solid rgba(255, 255, 255, 0.2);

            .avatar-mask {
              position: absolute;
              top: 0;
              left: 0;
              right: 0;
              bottom: 0;
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              background: rgba(0, 0, 0, 0.6);
              opacity: 0;
              transition: opacity 0.3s;

              .icon-camera {
                font-size: 24px;
                margin-bottom: 8px;
              }

              .text {
                font-size: 14px;
              }
            }

            &:hover .avatar-mask {
              opacity: 1;
            }
          }
        }

        .info-section {
          .name {
            font-size: 24px;
            font-weight: 500;
            margin: 0 0 12px;
          }

          .account-type {
            margin-bottom: 12px;
          }

          .brief {
            font-size: 14px;
            opacity: 0.8;
            max-width: 500px;
          }
        }
      }
    }
  }

  .overview-card {
    background-color: var(--color-bg-2);

    .stats-wrapper {
      padding: 24px;
    }

    .stats {
      display: flex;
      gap: 48px;

      .stat-item {
        .value {
          font-size: 24px;
          font-weight: 500;
          color: var(--color-text-1);
          line-height: 1.2;
        }

        .label {
          font-size: 14px;
          color: var(--color-text-3);
          margin-top: 4px;
        }
      }
    }
  }

  .general-card {
    background-color: var(--color-bg-2);
    height: 100%;

    :deep(.arco-card-header) {
      border-bottom: 1px solid var(--color-border);
    }

    .card-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .form-actions {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid var(--color-border);
  }

  .login-record {
    .time {
      font-size: 14px;
      color: var(--color-text-2);
      margin-bottom: 8px;
    }

    .info {
      font-size: 13px;
      color: var(--color-text-3);
      margin-bottom: 8px;

      > div {
        margin-bottom: 4px;
      }
    }
  }

  .pagination-wrapper {
    margin-top: 16px;
    display: flex;
    justify-content: center;
  }

  .stats-wrapper, .user-profile, .overview-card, .general-card {
    min-height: 20px; // 给元素一个最小高度，减少尺寸频繁变化
    will-change: transform; // 提示浏览器这个元素会变化，可能有助于性能
    transform: translateZ(0); // 触发GPU加速，减少重排
  }
}

@media screen and (max-width: 768px) {
  .profile-container {
    .profile-header {
      flex-direction: column;
      align-items: center;
      text-align: center;

      .profile-avatar {
        margin-right: 0;
        margin-bottom: 24px;
      }

      .profile-info {
        .stats {
          justify-content: center;
        }
      }
    }
  }
}
</style>
